package com.handle.http;

import com.protocol.RequestParser;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author linyu.dai
 * @project rpc
 * @description
 * @creat 2022/11/29 18:14:02
 */
@ChannelHandler.Sharable
@Slf4j
public class NettyHttpHandle extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        //获取请求
        log.info(msg.uri());
        log.info(msg.protocolVersion().toString());
        log.info("类型:{}",msg.headers().get("Content-Type"));
        log.info(msg.method().name());
        Map<String, String> paramMap = new RequestParser(msg).parse();
        log.info("param {}",paramMap);

        DefaultFullHttpResponse response;

        if (msg.uri().contains(".")){
            //说明是文件类型
            response = HttpFileRequestHandle.process(msg.uri());
        }else{
            //处理接口类型
            response = HttpRequestHandle.process(msg, paramMap);
        }

//        //返回响应
//        DefaultFullHttpResponse response = new DefaultFullHttpResponse(msg.protocolVersion(), HttpResponseStatus.OK);
//
//        byte[] bytes = "<h1>Hello,World</h1>".getBytes();
//        response.content().writeBytes(bytes);
//        //告诉http响应的长度 防止浏览器转圈
//        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH,bytes.length);

        //写回响应
        ctx.writeAndFlush(response);
    }

}
